package com.atguigu.lease.common.utils;

import cn.hutool.core.util.IdUtil;
import com.atguigu.lease.common.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * jwt工具类
 *
 * @Author mr.luo
 * @Date 21 5月 2025 11:07
 */
@Component
public class JwtUtil {
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 创建token
     *
     * @param id
     * @return
     */
    public String createJwt(Long id) {
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtProperties.getSecret())
                .setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getExpire()))
                .setId(IdUtil.fastSimpleUUID())
                .claim("id", id)
                .compact();
        return token;
    }

    /**
     * 解析token
     */
    public Claims parseJwt(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(jwtProperties.getSecret())
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims;
//        Claims claims = Jwts.parser()
//                .setSigningKey(jwtProperties.getSecret())
//                .parseClaimsJws(token)
//                .getBody();
//        return claims;
    }
}
